import platform, os
from hashlib import md5
import psutil


def get_hostname():
    h = os.popen("hostname")
    return h.read().strip()


# 获取服务器运行时间
def get_uptime():
    f = open('/proc/uptime','r')
    r = f.read()
    u = r.split()
    f.close()
    uptime = format_seconds(int(float(u[0])))
    cpu_num = os.popen("cat /proc/cpuinfo  | grep processor | wc -l")
    cpu_num = int(cpu_num.read().strip())
    free = int(float(u[1]) * 100 / (float(u[0])*cpu_num))
    uptime['free'] = free
    return uptime


def format_seconds(s):
    s = int(s)
    D = 0
    H = 0
    M = 0
    S = s
    if S > 59:
        M = int(S / 60)
        S = S % 60
        if M > 59:
            H = int(M / 60)
            M = M % 60
            if H > 23:
                D = int(H / 24)
                H = H % 24
    return { 'days':D, 'hours':H, 'minutes':M, 'seconds':S }


def get_ip():
    r = os.popen("ip a | grep inet | grep -Ev 'inet6|127.0.0.1' | awk -F'[ /]+' '{print $3}'")
    r = r.read()
    ip = r.split()
    if len(ip) > 1:
        ip = ', '.join(ip)
    else:
        ip = ip[0]
    return ip


def get_load():
    f = open('/proc/loadavg')
    l = f.read().split()
    f.close()
    loadavg_1 = l[0]
    loadavg_5 = l[1]
    loadavg_15 = l[2]
    return [loadavg_1,loadavg_5,loadavg_15]


def get_mem():
    f = open('/proc/meminfo')
    m = f.readlines()
    f.close()
    mem = {}
    for n in m:
        if len(n) < 2 : continue
        name = n.split(':')[0]
        var = n.split()[1]
        mem[name] = int(var) * 1024 # 单位默认是K，乘以1024转换为字节
    mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
    MemUsedPercent = int(mem['MemUsed'] * 100 / mem['MemTotal'])
    mem['MemUsedPercent'] = MemUsedPercent
    return mem


def get_hdd():
    d = os.statvfs('/')
    all = d.f_frsize * d.f_blocks
    free = d.f_frsize * d.f_bavail
    used = ( d.f_blocks - d.f_bavail ) * d.f_frsize
    usedPercent = int(( d.f_blocks - d.f_bavail ) * 100 / d.f_blocks)
    return {"all":all, "free":free, "used":used, "usedPercent":usedPercent}


def net_stat():
    net = {}
    f = open("/proc/net/dev")
    lines = f.readlines()
    f.close()
    i = 1
    for line in lines:
        if i < 3 :
           i += 1
           continue
        con = line.split(':')
        name = con[0].split()[0]
        var = con[1].split()
        net[name] = var
        i += 1
    net_in = 0
    net_out = 0
    for i in net:
        if i == 'lo':continue
        net_in += int(net[i][0])
        net_out += int(net[i][8])
    return {"in":net_in,"out":net_out}


def get_os_version():
    OS = platform.linux_distribution()
    os_arch = platform.machine()
    if 'Red Hat Enterprise Linux Server' in OS:
        os_name = 'RHEL'
    else:
        os_name = OS[0]
    os_version = OS[1]
    return "%s %s %s" % ( os_name,os_version,os_arch)


def get_dnsmasq():
    status = os.system("ps -ef|grep dnsmasq|grep -v grep >>/dev/null")
    v1 = os.popen("dnsmasq --version | head -1 | awk '{print $3}'")
    version = v1.read().strip()
    return {"version": version, "status": status}


def get_cpu():
    cpu = psutil.cpu_percent(None)
    return cpu


def get_md5(file):
    m = md5()
    # 需要使用二进制格式读取文件内容
    f = open(file, 'rb')
    m.update(f.read())
    f.close()
    return m.hexdigest()